// products.ts
// 导入API工具
import { productApi, saleApi, Product, ProductCategory } from '../../utils/api'

Component({
  data: {
    currentCategory: 'all',
    searchKeyword: '',
    cartCount: 0,
    categories: [
      { id: 'all', name: '全部', code: 'all', sort: 0 }
    ] as ProductCategory[],
    products: [] as Product[],
    filteredProducts: [] as Product[],
    loading: false,
    error: null as string | null,
    showModal: false,
    selectedProduct: {} as Product,
    quantity: 1,
    totalPrice: 0
  },

  methods: {
    handlerGobackClick() {
      wx.navigateBack({
        delta: 1
      })
    },
    // 获取产品分类
    async loadCategories() {
      try {
        // 使用API工具获取分类
        const response = await productApi.getProductCategories()
        
        if (response.code === 200) {
          const categories = [
            { id: 'all', name: '全部', code: 'all', sort: 0 },
            ...response.data
          ]
          this.setData({ categories })
        } else {
          throw new Error('获取分类失败')
        }
      } catch (error) {
        console.error('获取分类失败:', error)
      }
    },

    // 获取产品列表
    async loadProducts() {
      try {
        this.setData({ loading: true })
        
        // 使用API工具获取产品列表
        const response = await productApi.getProductList({})
        
        if (response.code === 200) {
          this.setData({ products: response.data })
          this.filterProducts()
        } else {
          throw new Error('获取产品失败')
        }
      } catch (error) {
        console.error('获取产品失败:', error)
        // 使用模拟数据
        this.loadMockProducts()
      } finally {
        this.setData({ loading: false })
      }
    },

    // 加载模拟数据
    loadMockProducts() {
      const mockProducts = [
      ]
      this.setData({ products: mockProducts })
      this.filterProducts()
    },

    // 切换分类
    switchCategory(e: any) {
      const category = e.currentTarget.dataset.category
      this.setData({ currentCategory: category })
      this.filterProducts()
    },

    // 搜索产品
    onSearch(e: any) {
      const keyword = e.detail.value.toLowerCase()
      this.setData({ searchKeyword: keyword })
      this.filterProducts()
    },

    // 过滤产品
    filterProducts() {
      const { products, currentCategory, searchKeyword } = this.data
      let filtered = products

      // 按分类过滤
      if (currentCategory !== 'all') {
        filtered = filtered.filter(item => item.category === currentCategory)
      }

      // 按关键词搜索
      if (searchKeyword) {
        filtered = filtered.filter(item => 
          item.name.toLowerCase().includes(searchKeyword) ||
          item.description.toLowerCase().includes(searchKeyword)
        )
      }

      this.setData({ filteredProducts: filtered })
    },

    // 跳转到产品详情
    goToProductDetail(e: any) {
      const id = e.currentTarget.dataset.id
      wx.navigateTo({
        url: `/pages/product-detail/product-detail?id=${id}`
      })
    },

    // 添加到购物车
    addToCart(e: any) {
      const id = e.currentTarget.dataset.id
      const product = this.data.products.find(p => p.id === id)
      
      if (product) {
        // 获取现有购物车
        const cart = wx.getStorageSync('cart') || []
        
        // 检查商品是否已存在
        const existingItem = cart.find((item: any) => item.id === id)
        if (existingItem) {
          existingItem.quantity += 1
        } else {
          cart.push({
            ...product,
            quantity: 1,
            selected: true
          })
        }
        
        // 保存购物车
        wx.setStorageSync('cart', cart)
        
        // 更新购物车数量
        const cartCount = cart.reduce((sum: number, item: any) => sum + item.quantity, 0)
        this.setData({ cartCount })
        
        wx.showToast({
          title: '已添加到购物车',
          icon: 'success'
        })
      }
    },

    // 跳转到购物车
    goToCart() {
      wx.navigateTo({
        url: '/pages/cart/cart'
      })
    },

    // 显示购买弹窗
    showBuyModal(e: any) {
      const product = e.currentTarget.dataset.product
      const totalPrice = product.price * this.data.quantity
      this.setData({
        showModal: true,
        selectedProduct: product,
        quantity: 1,
        totalPrice: totalPrice
      })
    },

    // 关闭弹窗
    closeModal() {
      this.setData({
        showModal: false,
        selectedProduct: {},
        quantity: 1,
        totalPrice: 0
      })
    },

    // 增加数量
    increaseQuantity() {
      const newQuantity = this.data.quantity + 1
      const totalPrice = this.data.selectedProduct.price * newQuantity
      this.setData({
        quantity: newQuantity,
        totalPrice: totalPrice
      })
    },

    // 减少数量
    decreaseQuantity() {
      if (this.data.quantity > 1) {
        const newQuantity = this.data.quantity - 1
        const totalPrice = this.data.selectedProduct.price * newQuantity
        this.setData({
          quantity: newQuantity,
          totalPrice: totalPrice
        })
      }
    },

    // 提交订单
    async submitOrder() {
      const { selectedProduct, quantity } = this.data
      
      if (!selectedProduct.id) {
        wx.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return
      }

      try {
        wx.showLoading({
          title: '提交中...'
        })

        const userInfo = wx.getStorageSync('userInfo')

        // 调用销售API提交订单
        const orderData = {
          productId: selectedProduct.id,
          productName: selectedProduct.name,
          unitPrice: selectedProduct.price,
          quantity: quantity,
          totalAmount: selectedProduct.price * quantity,
          memberId: userInfo.id,
          memberName: userInfo.name
        }

        const res = await saleApi.purchase(orderData)
        if (res.code !== 200) throw new Error(res.message || '下单失败')

        wx.hideLoading()
        
        // 关闭弹窗
        this.closeModal()
        
        wx.showToast({
          title: '购买成功',
          icon: 'success'
        })

        // 跳转到订单页面
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/my-products/my-products'
          })
        }, 1500)

      } catch (error) {
        wx.hideLoading()
        wx.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        })
      }
    }
  },

  lifetimes: {
    async attached() {
      // 加载分类和产品数据
      await Promise.all([
        this.loadCategories(),
        this.loadProducts()
      ])
      
      // 更新购物车数量
      const cart = wx.getStorageSync('cart') || []
      const cartCount = cart.reduce((sum: number, item: any) => sum + item.quantity, 0)
      this.setData({ cartCount })
    }
  },
})